package com.by;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


public class Publisher {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        //1. 创建连接 实例化连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务器地址
        factory.setHost("192.168.131.128");
        //设置账号 密码
        factory.setUsername("admin");
        factory.setPassword("123456");
        //设计端口号
        factory.setPort(5672);

        //设计虚拟主机
        factory.setVirtualHost("/");

        //2创建链接
        Connection conn = factory.newConnection();

        //3.创建信道
        Channel channel = conn.createChannel();

        //4开启确认发布
        channel.confirmSelect();
        //5声明队列
        String queue="batchSingle";
        channel.queueDeclare(queue,true,false,false,null);

        //增加监听 接收服务器返回的确认消息  接收服务器返回 是异步的
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("---------确认消息" + deliveryTag+"   "+multiple);
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {

            }
        });


        long begin=System.currentTimeMillis();//开始时间
        int count=1000;//模拟发送消息的数量
        int batchSize=15; //每次发送多少条确认
        int tmp=0;

        for(int i=0;i<count;i++){
            String msg="消息"+i;
            channel.basicPublish("",queue, MessageProperties.PERSISTENT_TEXT_PLAIN,msg.getBytes());
            System.out.println(msg+"   已发送"+channel.getNextPublishSeqNo());

            if((tmp = i % batchSize)==0)
            //等待服务器返回确认
            channel.waitForConfirmsOrDie(1000);
        }
        if (tmp != 0)
            channel.waitForConfirmsOrDie(1000);
        System.out.println("耗时："+(System.currentTimeMillis()-begin));

        System.out.println("----消息已发送！");

        //关闭连接  释放资源
        channel.close();
        conn.close();








    }
}
